package com.yjkf.zh.admin.aspect;

import com.yjkf.zh.admin.model.SysLog;
import com.yjkf.zh.admin.security.SecurityUtils;
import com.yjkf.zh.admin.service.SysLogService;
import com.yjkf.zh.admin.util.HttpUtils;
import com.yjkf.zh.admin.util.IPUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

   // @Pointcut("execution(* com.yjkf.zh.*.service.*.*(..))")
   @Pointcut("@annotation(com.yjkf.zh.admin.aspect.LogAnnotation)")
    public void logPointCut(){

    }


    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        long beginTime = System.currentTimeMillis();        //获取当前系统时间
        //执行方法
        Object result = point.proceed();        //获取当前执行的方法
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        saveSysLog(point,time);
        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint,long time){
        String userName = SecurityUtils.getUsername();
        if(joinPoint.getTarget() instanceof SysLogService){
            return ;
        }
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        SysLog sysLog = new SysLog();
        Method method = signature.getMethod();
        LogAnnotation syslogAnno = method.getAnnotation(LogAnnotation.class);

        if(syslogAnno != null) {
//			//注解上的描述
            sysLog.setOperation(syslogAnno.content());
        }
        //请求方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className+"."+methodName+"()");
        //请求的参数
      //  Object[] args = joinPoint.getArgs();

            //获取request
        HttpServletRequest request = HttpUtils.getHttpServletRequest();
        //设置IP地址
        sysLog.setIp(IPUtil.getIpAddr(request));
        sysLog.setUserName(userName);
        sysLog.setTime(time);//执行时长

        //保存系统日志
        sysLogService.save(sysLog);
    }
}
